package com.smt.modules.bus.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.enums.Code;
import com.smt.common.enums.StageEnum;
import com.smt.common.utils.Constant;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.common.utils.R;
import com.smt.common.utils.StringUtil;
import com.smt.modules.bus.dao.MemberUserDao;
import com.smt.modules.bus.entity.*;
import com.smt.modules.bus.pojo.ProjectSiPojo;
import com.smt.modules.bus.pojo.TeamManagePojo;
import com.smt.modules.bus.service.*;
import com.smt.modules.bus.vo.TeamVo;
import com.smt.modules.bus.vo.request.ProjectSiReq;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 团队管理实现类
 *
 * @author zhangyi
 * @date 2018/10/10 15:13
 */
@Service
public class TeamManagementServiceImpl extends ServiceImpl<MemberUserDao, MemberUserEntity> implements TeamManagementService {

    @Autowired
    private SubtaskService subtaskService;

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private MemberUserService memberUserService;

    @Autowired
    private InviteService inviteService;

    @Autowired
    private ProjectService projectService;

    /**
     * 获取该项目下的成员列表
     *
     * @param projectSiReq
     * @return
     */
    @Override
    public R list(ProjectSiReq projectSiReq) {
        @NotNull(message = "项目id") Long projectId = projectSiReq.getProjectId();
        Integer stage = projectSiReq.getStage();
        ProjectSiPojo p = new ProjectSiPojo();
        BeanUtils.copyProperties(projectSiReq, p);
        Wrapper<ProjectTaskEntity> projectWrapper = new EntityWrapper<ProjectTaskEntity>()
                .eq("project_id", projectId)
                .eq("member_exist", 0);
        //去除重复用户信息
        Map<Long, MemberUserEntity> memberMap = new ConcurrentHashMap<>();
        //全部用户
        if (stage.equals(0)) {
            projectWrapper.in("stage_id", "1,2,3,4,5,6");
        } else {
            projectWrapper.eq("stage_id", stage)
                    .in("status", Constant.SQL_CON);

        }
        List<ProjectTaskEntity> projectTaskEntityList = projectTaskService.selectList(projectWrapper);
        if (projectTaskEntityList != null && projectTaskEntityList.size() != 0) {
            projectTaskEntityList.stream()
                    .forEach(sm -> {
                        //设置创建者id
                        TeamEntity teamEntity = teamService.selectOne(new EntityWrapper<TeamEntity>()
                                .eq("member_id", sm.getMemberId())
                                .eq("member_exist", 0)
                                .eq("project_id", sm.getProjectId()));
                        if (teamEntity != null) {
                            Long memberId = sm.getMemberId();
                            Long stageMemberId = sm.getStageMemberId();
                            if (memberId != null && memberMap.get(memberId) == null) {
                                MemberUserEntity memberUserEntity =
                                        memberUserService.selectOne(new EntityWrapper<MemberUserEntity>().eq("user_id", memberId));
                                if (memberUserEntity != null) {
                                    memberUserEntity.setPassword(null);
                                    memberUserEntity.setStageId(sm.getStageId());
                                    memberMap.put(memberId, memberUserEntity);
                                }
                            }
                            //阶段负责人
                            if (stageMemberId != null) {
                                MemberUserEntity stageMemberUserEntity =
                                        memberUserService.selectOne(new EntityWrapper<MemberUserEntity>().eq("user_id", stageMemberId));
                                if (stageMemberUserEntity != null) {
                                    stageMemberUserEntity.setStageId(stage);
                                    memberMap.put(stageMemberUserEntity.getUserId(), stageMemberUserEntity);
                                }
                            }
                            //该任务下的子任务成员列表
                            List<SubtaskEntity> subMemberList = subtaskService.selectList(new EntityWrapper<SubtaskEntity>()
                                    .eq("project_task_id", sm.getId())
                                    .eq("member_exist", 0));
                            if (subMemberList != null && subMemberList.size() != 0) {
                                subMemberList.stream().forEach(s -> {
                                    Long subMemberId = s.getMemberId();
                                    if (subMemberId != null && memberMap.get(subMemberId) == null) {
                                        MemberUserEntity memberUserEntity =
                                                memberUserService.selectOne(new EntityWrapper<MemberUserEntity>().eq("user_id", subMemberId));
                                        if (memberUserEntity != null) {
                                            memberUserEntity.setPassword(null);
                                            memberUserEntity.setStageId(sm.getStageId());
                                            memberMap.put(subMemberId, memberUserEntity);
                                        }
                                    }
                                });
                            }
                        }
                    });

        }
        //将获取到的全部成员 非任务成员加入进来
        if (stage.equals(0)) {
            //添加创建者
            ProjectEntity projectEntity = projectService.selectById(projectId);
            //项目下的成员列表（添加未分配的成员）
            List<TeamEntity> projectList = teamService.selectList(new EntityWrapper<TeamEntity>()
                    .eq("project_id", projectId)
                    .eq("member_exist", 0));
            projectList.stream().map(TeamEntity::getMemberId)
                    .forEach(pp -> {
                        if (memberMap.get(pp) == null) {
                            MemberUserEntity memberUserEntity = memberUserService.selectOne(new EntityWrapper<MemberUserEntity>().eq("user_id", pp));
                            memberMap.put(pp, memberUserEntity);
                        }
                    });

            //添加已分配的成员的阶段名
            List<ProjectTaskEntity> projectTaskEntities = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                    .eq("project_id", projectId)
                    .eq("member_exist", 0));

            if (projectEntity != null && projectTaskEntities != null && projectTaskEntities.size() != 0) {
                Long createdId = projectEntity.getCreatedId();
                Set<Long> longs = memberMap.keySet();
                Iterator<Long> iterator = longs.iterator();
                while(iterator.hasNext()){
                    Long memberId = iterator.next();
                    //任务id
                    for(ProjectTaskEntity pro : projectTaskEntities){
                        Long proMemberId = pro.getMemberId();
                        Integer stageId = pro.getStageId();
                        Long id = pro.getId();
                        //排除创建者的id
                        if(proMemberId != null && !proMemberId.equals(createdId)){
                            //匹配本次任务的责任人
                            if(memberId.equals(proMemberId)){
                                MemberUserEntity memberUserEntity = memberUserService.selectById(proMemberId);
                                memberUserEntity.setStageId(stageId);
                                memberMap.put(proMemberId,memberUserEntity);
                            }else{
                                //从当前子任务查找
                                List<SubtaskEntity> subtaskEntities = subtaskService.selectList(new EntityWrapper<SubtaskEntity>()
                                        .eq("project_task_id", id));
                                for (SubtaskEntity s : subtaskEntities){
                                    Long sMemberId = s.getMemberId();
                                    if(sMemberId != null && !sMemberId.equals(createdId)){
                                        if(sMemberId.equals(memberId)){
                                            MemberUserEntity memberUserEntity = memberUserService.selectById(sMemberId);
                                            memberUserEntity.setStageId(stageId);
                                            memberMap.put(sMemberId,memberUserEntity);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (projectEntity != null) {
                MemberUserEntity memberUserEntity = memberUserService.selectById(projectEntity.getCreatedId());
                memberUserEntity.setMyMine(1);
                memberMap.put(memberUserEntity.getUserId(), memberUserEntity);
            }
        }
        return R.ok().put("members", memberMap);
    }

    /**
     * 上传头像
     *
     * @return
     */
    @Override
    public R uploadHeadImg(String headImg, MemberUserEntity memberUserEntity) {
        memberUserEntity.setHeadImg(headImg);
        if (!headImg.equals(null)) {
            boolean b = updateById(memberUserEntity);
            return b ? R.ok() : R.error(EnumToKeyUtil.toInt(com.smt.common.enums.Code.UPDATE_FAIL), "上传头像失败");
        } else {
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "上传头像失败");
        }
    }

    /**
     * 移除项目用户
     *
     * @param projectId
     * @param userId
     * @return
     */
    @Override
    public R remove(Long projectId, Long userId, MemberUserEntity entity) {
        if (userId.equals(entity.getUserId())) {
            return R.error("您不能删除自己").put("status", EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR));
        }
        //权限检测
        Long creatorId = baseMapper.selectCreator(projectId);
        TeamManagePojo teamManagePojo = new TeamManagePojo();
        teamManagePojo.setUserId(userId);
        teamManagePojo.setProjectId(projectId);
        if (creatorId == null) {
            return R.error(EnumToKeyUtil.toInt(Code.QUERY_DATA_ERROR), "项目不存在");
        }
        if (creatorId.equals(entity.getUserId())) {
            //移除任务
            int i = baseMapper.updateMemberById(teamManagePojo);
            List<ProjectTaskEntity> projectTaskEntityList = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                    .eq("project_id", projectId));
            projectTaskEntityList.stream().forEach(p -> {
                Long id = p.getId();
                //移除阶段责任人
                if (p.getStageMemberId().equals(userId)) {
                    //将阶段初始为有效位
                    ProjectTaskEntity projectTaskEntityStage = new ProjectTaskEntity();
                    projectTaskEntityStage.setStageMemberId(new Long(0));
                    projectTaskService.update(projectTaskEntityStage, new EntityWrapper<ProjectTaskEntity>()
                            .eq("project_id", p.getProjectId())
                            .eq("stage_member_id", userId));
                }
                if (p.getMemberId().equals(userId)) {
                    ProjectTaskEntity projectTaskEntityMember = new ProjectTaskEntity();
                    projectTaskEntityMember.setMemberId(new Long(0));
                    projectTaskService.update(projectTaskEntityMember, new EntityWrapper<ProjectTaskEntity>()
                            .eq("project_id", p.getProjectId())
                            .eq("member_id", userId));
                }
                List<SubtaskEntity> sE = subtaskService.selectList(new EntityWrapper<SubtaskEntity>()
                        .eq("member_id", userId)
                        .eq("project_task_id", id));
                sE.stream().forEach(ss -> {
                    SubtaskEntity subtaskEntity = new SubtaskEntity();
                    subtaskEntity.setId(ss.getId());
                    subtaskEntity.setMemberId(new Long(0));
                    subtaskService.updateById(subtaskEntity);
                });
            });
            //将团队成员删除
            TeamEntity teamEntity = new TeamEntity();
            teamEntity.setMemberExist(1);
            boolean update = teamService.update(teamEntity, new EntityWrapper<TeamEntity>()
                    .eq("project_id", projectId)
                    .eq("member_id", userId)
                    .eq("createor_id", entity.getUserId()));
            //删除邀请记录
            List<TeamEntity> teamEntity1 = teamService.selectList(new EntityWrapper<TeamEntity>()
                    .eq("project_id", projectId));
            Long teamId = new Long(0);
            for (TeamEntity t : teamEntity1) {
                if (t.getCreateorId().equals(t.getMemberId())) {
                    teamId = t.getId();
                    break;
                }
            }
            MemberUserEntity memberUserEntity = memberUserService.selectById(userId);
            if (memberUserEntity != null) {
                //暂时是邮箱邀请
                inviteService.delete(new EntityWrapper<InviteEntity>()
                        .eq("team_id", teamId)
                        .eq("to_user", memberUserEntity.getEmail()));
            }
            return ((i == 0) && !update) ? R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR), "移除失败！") : R.ok("移除成功");
        } else {
            //不能
            return R.error(EnumToKeyUtil.toInt(Code.MISSING_PERMISSION), "您的权限不够！");
        }
    }

    /**
     * 加入该公司
     *
     * @param creatorId
     * @param memberUserEntity
     * @return
     */
    @Override
    public R join(Long creatorId, MemberUserEntity memberUserEntity) {
        TeamVo teamVo = new TeamVo();
        teamVo.setConfirm(2);
        teamVo.setCreateorId(creatorId);
        teamVo.setMemberId(memberUserEntity.getUserId());
        teamVo.setCreateTime(DateTime.now().toDate());
        return 0 == baseMapper.updateJoin(teamVo) ? R.ok("加入该公司成功") :
                R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR), "加入该公司失败");
    }

    @Override
    public List<TeamEntity> getMemberList(Long creatorId) {
        return baseMapper.selectMemberList(creatorId);
    }

    @Override
    public R teamMembers(Long teamId, MemberUserEntity memberUserEntity) {
        List<Long> memberByTeam = baseMapper.getMemberByTeam(teamId);
        return R.ok().put("teams", memberByTeam);
    }

    /**
     * 在创建一个项目的时候哦创建一个团队
     *
     * @param creatorId
     * @return
     */
    @Override
    public boolean createTeam(Long creatorId, Long projectId) {
        //查找当前创建者的项目创建条数
//        List<TeamEntity> teamList = teamService.selectList(new EntityWrapper<TeamEntity>()
//                .eq("createor_id", creatorId));
        boolean[] flag = new boolean[]{true};
        //是否有删除的项目
//        teamList.stream().forEach(t -> {
//            if(t.getProjectId().equals(0)){
//                //更新项目
//                t.setProjectId(projectId);
//                boolean b = teamService.updateById(t);
//                if(b){
//                    flag[0] = false;
//                }
//            }
//        });
        if (flag[0]) {
            //生成团队标识码
            String teamId = StringUtil.generateString(6);
            //创建团队
            TeamEntity teamEntity = new TeamEntity();
            teamEntity.setMemberId(creatorId);
            teamEntity.setConfirm(2);
            teamEntity.setCreateTime(DateTime.now().toDate());
            teamEntity.setCreateorId(creatorId);
            teamEntity.setToken(teamId);
            teamEntity.setProjectId(projectId);
            boolean insert = teamService.insert(teamEntity);
            //将此时的团队id设置成当前的团队id
            teamEntity.setBusTeamId(teamEntity.getId());
            boolean b = teamService.updateById(teamEntity);
            return b && insert;
        } else {
            return false;
        }
    }
}
